package org.nvframe.manager;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.newdawn.slick.Input;
import org.nvframe.exception.NVFrameException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 
 * @author Nik Van Looy
 */
public class InputManager {

	private final static InputManager _instance = new InputManager();

	public static InputManager getInstance() {
		return _instance;
	}
	
	private static HashMap<String, Integer> keyMap;

	private InputManager() {
		keyMap = new HashMap<String, Integer>();
	}
	
	public void addInput(String inputName, int keyCode) {
		keyMap.put(inputName, keyCode);
	}
	
	public int getInput(String inputName) {
		return keyMap.containsKey(inputName) ? keyMap.get(inputName) : null;
	}
	
	
	
	public void loadInputKeys(InputStream is) throws NVFrameException {
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = null;
		
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new NVFrameException("Could not load keymap xmlfile", e);
		}
		
		Document doc = null;
		
		try {
			doc = docBuilder.parse(is);
		} catch (SAXException e) {
			throw new NVFrameException("Could not load keymap xmlfile", e);
		} catch (IOException e) {
			throw new NVFrameException("Could not load keymap xmlfile", e);
		}

		doc.getDocumentElement().normalize();

		// load the root tag
		NodeList listInputs = doc.getElementsByTagName("input");

		int totalInputs = listInputs.getLength();

		for (int inputId = 0; inputId < totalInputs; inputId++) {

			Node inputNode = listInputs.item(inputId);

			if (inputNode.getNodeType() == Node.ELEMENT_NODE) {
				Element resourceElement = (Element) inputNode;

				String inputName = resourceElement.getAttribute("id");
				String inputKey = resourceElement.getTextContent();

				try {
					Field inputProp = Input.class.getField(inputKey);
					addInput(inputName, (Integer) inputProp.get(null));
				} catch (IllegalAccessException e) {
					throw new NVFrameException("Inputkey not found", e);
				} catch (SecurityException e) {
					throw new NVFrameException("Inputkey not found", e);
				} catch (NoSuchFieldException e) {
					throw new NVFrameException("Inputkey not found", e);
				}
				
			}
		}
	}

}
